package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateTC
 */
//@WebServlet(description = "更新測試案例", urlPatterns = { "/UpdateTC" })
public class UpdateTC extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateTC() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tcID = request.getParameter("q_tcID"); // 測試案例ID
		String strRes = ""; // 最後執行的結果回傳
		Widgets wid = new Widgets();

		
		/**
		 * 我們在 tms_testCase中，讓MySQL自動以流水號產生uID 但因為我們要拿此uID與 tcID 寫入 Mapping
		 * 因此我們在insert完 tms_testCase(測試案例維護表) 後，立刻以同一個'創建者'，'最新時間'為條件
		 * 立該查出該筆產生的uID，再拿來寫入對應表 (tms_tcidmapping)
		 **/
		long uID = 0;

		String tcName = request.getParameter("tcName"); // 測試案例名稱
		String tcKeyPoint = request.getParameter("tcKeyPoint"); // 驗証重點
		String tcProcess = request.getParameter("tcProcess"); // 測試程序
		String tcResExp = request.getParameter("tcResExp"); // 預期結果
		String tmp = request.getParameter("isAct");
		boolean isActive = tmp.equalsIgnoreCase("chk")?true:false; // 預期結果
		String tcTestData = request.getParameter("tcTestData"); // 預期結果
		String creator = request.getParameter("loginUser"); // 創建者
		String numKeyPoint = request.getParameter("tcNumKeyPoint");
		Timestamp currentTime = wid.currentTimeStamp();

		// 新增測試案例一筆新記錄
		String strInsertTC = "INSERT INTO tms_testcase(uID,numKeyPoint,tcName,tcKeyPoint,tcProcess,tcResExp,Creator,tcTestData,CreatedDateTime,LastUpdatedTime)VALUES(NULL,?,?,?,?,?,?,?,?,?)";

		/* 取得系統產生的uID */
		String strSQLuID = "SELECT uID FROM tms_testcase t1 WHERE t1.Creator=? ORDER BY t1.uID DESC";

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strInsertTC);
			ps.setString(1, numKeyPoint);
			ps.setString(2, tcName);
			ps.setString(3, tcKeyPoint);
			ps.setString(4, tcProcess);
			ps.setString(5, tcResExp);
			ps.setString(6, creator);
			ps.setString(7, tcTestData);
			ps.setTimestamp(8, currentTime);
			ps.setTimestamp(9, currentTime);
			ps.execute();
			ps = conn.prepareStatement(strSQLuID);
			ps.setString(1, creator);
			rs = ps.executeQuery();
			rs.next();
			uID = rs.getInt("uID");
			
			String strUpdateMapping_1 = "";
			if (isActive) {
				strUpdateMapping_1 = "UPDATE tms_tcidmapping SET active=false WHERE tcID=?";
				ps.clearBatch();
				ps = conn.prepareStatement(strUpdateMapping_1);
				ps.setString(1, new String(tcID.getBytes("iso-8859-1"),"UTF-8"));
				ps.executeUpdate();
			}
			
			
			// 新增Mapping表一筆新記錄
			String strInsertMapping = "INSERT INTO tms_tcidmapping(tcID,uID,active,LastUpdateID,LastUpdatedTime)VALUES(?,?,?,?,?)";
			ps = conn.prepareStatement(strInsertMapping);
			ps.setString(1, wid.changeCode(tcID));
			ps.setLong(2, uID);
			ps.setBoolean(3, isActive);
			ps.setString(4, creator);
			ps.setTimestamp(5, currentTime);
			ps.executeUpdate();
			
			wid.keepLogTC(tcID, uID, creator, 2, conn, ps);
			
			strRes = "修改測試案例成功!!";

		} catch (SQLException e) {
			wid.keepErrorMes(conn, ps, e, "", true);
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				strRes = e.toString();
				System.out.println(strRes);
			}
		}

		response.setContentType("application/text");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(strRes);
	}
}
